package com.btcode.security;

import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Hex;

public class ThreeDESUtil {

    static String algorithm = "DESede";
    static String PASSWORD_CRYPT_KEY = "48f3ae07-75f9-4ad2-be62-6a30aa0df4c3";

    public static void main(String[] args) throws Exception {

        String userid = "48f3ae07-75f9-4ad2-be62-6a30aa0df4c3,2018-7-19";

        String encodestr = encode(userid);
        String decodeStr = decode(encodestr);

        System.out.println("输入:" + userid);
        System.out.println("加密:" + encodestr);
        System.out.println("解密:" + decodeStr);

    }

    /**
     * 加密
     */
    public static String encode(String msg) throws Exception {
        SecureRandom sr = new SecureRandom();
        SecretKey securekey = new SecretKeySpec(build3DesKey(PASSWORD_CRYPT_KEY), algorithm);

        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);

        byte[] encodeByte = cipher.doFinal(msg.getBytes("UTF-8"));

        String result = new String(Hex.encodeHex(encodeByte));

        return result;
    }

    /**
     * 根据字符串生成密钥字节数组
     *
     * @param keyStr 密钥字符串
     */
    private static byte[] build3DesKey(String keyStr) throws UnsupportedEncodingException {
        /**
         * 声明一个24位的字节数组，默认里面都是0
         */
        byte[] key = new byte[24];
        /**
         * 将字符串转成字节数组
         */
        byte[] temp = keyStr.getBytes("UTF-8");

        /**
         * 执行数组拷贝
         * System.arraycopy(源数组，从源数组哪里开始拷贝，目标数组，拷贝多少位)
         */
        if (key.length > temp.length) {
            /**
             * 如果temp不够24位，则拷贝temp数组整个长度的内容到key数组中
             */
            System.arraycopy(temp, 0, key, 0, temp.length);
        }
        else {
            /**
             * 如果temp大于24位，则拷贝temp数组24个长度的内容到key数组中
             */
            System.arraycopy(temp, 0, key, 0, key.length);
        }
        return key;
    }

    /**
     * 解密函数
     *
     * @param src 密文的字节数组
     */
    public static String decode(String msg) throws Exception {
        SecretKey deskey = new SecretKeySpec(build3DesKey(PASSWORD_CRYPT_KEY), algorithm);
        Cipher c1 = Cipher.getInstance(algorithm);
        /**
         * 初始化为解密模式
         */
        c1.init(Cipher.DECRYPT_MODE, deskey);

        byte[] encodeByte = c1.doFinal(Hex.decodeHex(msg.toCharArray()));

        String result = new String(encodeByte);

        return result;
    }

}
